package com.youdoneed.base.application;

import com.youdoneed.base.common.JWTUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.support.RequestContext;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;

/**
 * 国际化消息转换类。
 */
public class RequestMessage {

    private RequestMessage() {
    }

    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public static RequestContext getRequestContext() {
        return new RequestContext(getRequest());
    }

    public static String getMessage(String name) {
        try {
            return getRequestContext().getMessage(name);
        } catch (Exception e) {
            return name;
        }
    }

    public static Locale getLocale() {
        return getRequestContext().getLocale();
    }

    public static String getLanguage() {
        return getLocale().getLanguage();
    }

    public static String getAuthUserId() {
        try {
            HttpServletRequest request = getRequest();
            String token = request.getHeader("Authorization");
            return (String) JWTUtils.getFromToken(token, "userId");
        } catch (Exception e) {
            throw new AppException("获取登陆的用户失败。");
        }
    }

}
